/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ncsu.csc.usart;

import com.sun.spot.peripheral.TimeoutException;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.peripheral.external.ExternalBoard;
import com.sun.spot.sensorboard.EDemoController;

import java.io.*;
/**
 *
 * @author Richard Pospesel
 */
public class USART
{
	private static EDemoBoard board = null;
	private static EDemoController controller = null;

	private static long timeout = 2000;
	private static InputStream in = null;
	private static OutputStream out = null;


	public static void initialize(int baud, int databits, int parity, int stopbits)
	{
		if(board == null)
		{
			board = EDemoBoard.getInstance();
			controller = board.getEDemoController();
			controller.initUART(baud, databits, parity, stopbits);
		}
		if(in == null || out == null)
		{
			in = new USARTInputStream();
			out = new USARTOutputStream();
		}
	}

	public static void setTimeout(long timeout)
	{
		USART.timeout = timeout;
	}

	public static InputStream getInputStream()
	{
		return in;
	}

	public static OutputStream getOutputStream()
	{
		return out;
	}

	public static int readUART() throws IOException
	{
		try
		{
			return controller.readUART(timeout);
		}
		catch(TimeoutException t)
		{
		}
		return -1;
	}

	public static int readUART(byte[] b) throws IOException
	{
		int bytes = b.length; 
		int count;
		for(count = 0; count < bytes; count++)
		{
			int read = readUART();
			if(read != -1)
				b[count] = (byte)read;
			else
				count--;
		}
		return bytes;
	}

	public static void writeUART(byte val)
	{
		controller.writeUART(val);
	}
}
